package com.hfi.restful.web.controller;

import com.hfi.restful.dto.Person;
import com.hfi.restful.exception.ErrorCode;
import com.hfi.restful.exception.MyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Size;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2019/9/21
 */
@RestController
@RequestMapping("/api")
@Validated
public class PersonController {

    /**
     * 修改PERSON
     * @PARAM PERSON
     * @RETURN
     */
    @PutMapping("/person")
    public Person updatePerson(@RequestBody @Valid Person person) {
        if (StringUtils.isEmpty(person.getClassId())) {
            Map<String, String> validMessages = new HashMap<>(1);
            validMessages.put("classId", "classId不能为空");
            throw new MyException(ErrorCode.PARAM_VALIDATION_FAIL, validMessages);
        }
        return person;
    }

    @GetMapping("/person")
    public Person getPersonByName(@Size(max = 6, message = "超过name的范围了") @RequestParam("name") String name) {
        return Person.builder().name(name).build();
    }

    @GetMapping("/person/{id}")
    public Integer getPersonById(@Max(value = 5, message = "超过id的范围了") @PathVariable("id") Integer id) {
        return id;
    }

    /**
     * 新增person
     * @param person
     * @return
     */
    @PostMapping("/person")
    public Person createPerson(@RequestBody @Valid Person person) {
        // ResponseEntity结果似乎可以看做是httpCodeValue + body的组合
        ResponseEntity<Person> body = ResponseEntity.ok().body(person);
        return body.getBody();
    }
}
